import MessageDetail from './messageDetail';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import { DATE_HMS } from '@/support/constant/common';
import { Card, Button, Table, message } from 'antd';
import { FormInstance } from 'antd/es/form';
import { connect } from 'dva';
import moment from 'moment';
import React, { useState, useMemo, useEffect, useRef } from 'react';

type MessageTabProps = {
  vehicleInfoQuery: any;
  dispatch: any;
  pageData: any;
  loading: boolean;
  pathname: string;
};

type MessageReport = {
  message: string;
  reportTime: string;
};

type MessageListFilter = {
  startTime: string;
  endTime: string;
};

const messageTab: React.FC<MessageTabProps> = props => {
  const { vehicleInfoQuery, loading, pageData } = props;
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const { list = [] } = pageData;
  const { vin } = vehicleInfoQuery;

  useEffect(() => {
    const { pageNum = 1, pageSize = 10, pageCount = 0 } = pageData;
    setPagination({
      current: pageNum,
      pageSize,
      total: pageCount,
    });
  }, [pageData]);

  const [reportTime, setReportTime] = useState('');
  const [view, switchView] = useState('list');
  const [isTablePagination, setIsTablePagination] = useState(false);

  const handleFieldsValue = (fieldsValue: MessageListFilter): MessageListFilter | boolean => {
    const validStartTime = moment(fieldsValue.endTime).subtract('1', 'd').subtract('1', 'm');
    if (moment(fieldsValue.startTime).isBefore(validStartTime)) {
      message.warning('时间范围不能超过1天，请重新选择');
      return false;
    }
    if (moment(fieldsValue.endTime).isBefore(moment(fieldsValue.startTime))) {
      message.warning('结束时间不能大于开始时间，请重新选择');
      return false;
    }

    const queryPagination = isTablePagination
      ? { pageNum: pagination.current, pageSize: pagination.pageSize }
      : { pageNum: 1, pageSize: 10 };
    setIsTablePagination(false);
    return {
      ...fieldsValue,
      ...queryPagination,
      startTime: moment(fieldsValue.startTime).format(DATE_HMS),
      endTime: moment(fieldsValue.endTime).format(DATE_HMS),
    };
  };
  const searchItems = [
    {
      title: '开始时间',
      type: 'datePicker',
      key: 'startTime',
      showTime: { format: DATE_HMS },
      format: DATE_HMS,
      rules: [{ required: false, message: '开始时间必填' }],
      initialValue: moment().subtract(1, 'day'),
    },
    {
      title: '结束时间',
      type: 'datePicker',
      showTime: { format: DATE_HMS },
      key: 'endTime',
      format: DATE_HMS,
      rules: [{ required: false, message: '结束时间必填' }],
      initialValue: moment(),
    },
  ];

  const handleDetail = (record: MessageReport) => {
    setReportTime(record.reportTime);
    switchView('detail');
  };

  const formRef = useRef(null);
  const fetchList = newPagination => {
    setPagination(newPagination);
    setIsTablePagination(true);
    formRef.current?.submit();
  };

  const handleFormRef = (form: { current: FormInstance }) => {
    formRef.current = form.current;
    formRef.current?.submit();
  };

  const columns = [
    {
      title: '上报时间',
      dataIndex: 'reportTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text: any, record: any) => {
        return (
          <Button type="primary" onClick={() => handleDetail(record)}>
            详情
          </Button>
        );
      },
    },
  ];

  const tableProps = {
    columns, // 列
    rowKey: (record: MessageReport, index: number) => {
      return record.reportTime + index
    }, // key
    loading, // 控制加载
    pagination,
    dataSource: list,
  };

  return view === 'list' ? (
    <>
      <PateoSearchForm
        onRef={handleFormRef}
        searchItems={searchItems}
        handleFieldsValue={handleFieldsValue}
        fetchParams={{ type: 'message/getFetchPage', url: '/message/parsing/list' }}
        extraArgs={{ vin }}
      />
      <Card title="报文列表" size="small" type="inner">
        <Table onChange={fetchList} size="small" {...tableProps} />
      </Card>
    </>
  ) : (
    <MessageDetail reportTime={reportTime} goBack={() => switchView('list')} />
  );
};

export default connect(({ vehicleInfoQuery, message, loading }) => ({
  vehicleInfoQuery,
  pageData: message.pageData,
  loading: loading.effects['message/getFetchPage'],
}))(messageTab);
